package org.codeart.singleton;

/**
 * 懒汉式，线程安全
 * 使用静态内部类保证线程安全
 * 静态内部类特性：懒加载，使用时才会加载
 */
public class Singleton05 {

    private Singleton05() {
//        if (SingletonHolder.singleton05 != null) {
//            throw new RuntimeException("instance is not null");
//        }
    }

    private static class SingletonHolder {
        private static final Singleton05 singleton05 = new Singleton05();
    }

    // 添加同步锁，保证多线程模式下单例模式线程安全
    public static synchronized Singleton05 getInstance() {
        return SingletonHolder.singleton05;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 50; i++) {
            new Thread(() -> {
                Singleton05 s = getInstance();
                System.out.println(Thread.currentThread().getName() + ": " + s);
            }).start();
        }
    }
}
